<template>
  <div>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="110px" :disabled="disableEditSubmit">
      <div class="meetTitle">
        <div class="square"></div>
        <label class="meetInfo">会议基本信息</label>
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="会议主题" prop="name" :rules="rules.validateRequire">
            <el-input v-model="model.name" placeholder="请输入会议主题"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="begintimeDate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.begintimeDate" type="date" placeholder="开始时间" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="10px" prop="begintimeTime" :rules="rules.validateRequire">
            <el-time-select
              v-model="model.begintimeTime"
              placeholder="选择时间"
              editable
              :clearable="false"
              :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00'
                  }"
            >
            </el-time-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endtimeDate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.endtimeDate" type="date" placeholder="结束时间" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="10px" prop="endtimeTime" :rules="rules.validateRequire">
            <el-time-select
              v-model="model.endtimeTime"
              placeholder="选择时间"
              editable
              :picker-options="{
                    start: '00:00',
                    step: '00:05',
                    end: '24:00'
                  }"
            >
            </el-time-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="会议类型" prop="meettypeid" :rules="rules.validateRequire">
            <el-cascader v-model="model.selectmeettypelist" :options="meetTypeList" style="width:350px" filterable @change="handleMeetTypeChange" clearable></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="meetTitle">
        <div class="square"></div>
        <label class="meetInfo">参会人员信息</label>
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item label="签到人员">
            <!--<tl-ref-mulit-user-select v-model="users.attend" :disabled="disableEditSubmit"></tl-ref-mulit-user-select>-->
            <tl-ref-user v-model="model.attendusercodes" :initDisplayData.sync="model.attendusernames" dataType="code" :singleSelect="false" :disabled="disableEditSubmit" :externalQueryParam="{qry_whereSql:'EXTENDFIELD1 IS NOT NULL AND ENABLED = 1',qry_nodimission:'0'}" ></tl-ref-user>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="缺席人员">
            <!--<tl-ref-mulit-user-select v-model="users.absent" :disabled="disableEditSubmit"></tl-ref-mulit-user-select>-->
            <tl-ref-user v-model="model.absentusercodes" :initDisplayData.sync="model.absentusernames" dataType="code" :singleSelect="false" :disabled="disableEditSubmit" :externalQueryParam="{qry_whereSql:'EXTENDFIELD1 IS NOT NULL AND ENABLED = 1',qry_nodimission:'0'}" ></tl-ref-user>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发起人" prop="launchusername" :rules="rules.validateRequire">
            <tl-ref-user v-model="model.launchusercode" :initDisplayData.sync="model.launchusername" dataType="code" :singleSelect="true" :disabled="disableEditSubmit" :externalQueryParam="{qry_whereSql:'EXTENDFIELD1 IS NOT NULL AND ENABLED = 1',qry_nodimission:'0'}" ></tl-ref-user>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发起组织类型" prop="launchorgtype" :rules="rules.validateRequire">
            <el-select v-model="model.launchorgtype" filterable clearable @change="clearOrgInfo">
              <el-option v-for="item in codeModel.launchorgtypeList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="model.launchorgtype">
          <el-form-item label="发起组织" prop="launchorgname" :rules="rules.validateRequire">
            <tl-ref-dept v-show="model.launchorgtype === 'dept'" v-model="model.launchorgindex" :initDisplayData.sync="model.launchorgname" nameType="fullname" dataType="code" :singleSelect="true" :disabled="disableEditSubmit"></tl-ref-dept>
            <tl-ref-list v-show="model.launchorgtype === 'team'" v-model="model.launchorgindex" :initDisplayData.sync="model.launchorgname" refTitle="管理团队选择" dataType="id" :queryDataUrl="url.queryTeamList" :singleSelect="true" :disabled="disableEditSubmit"></tl-ref-list>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="meetTitle">
        <div class="square"></div>
        <label class="meetInfo">额外授权人员</label>
      </div>
      <el-row>
        <el-col :span="23">
          <el-form-item label="纪要授权">
            <tl-ref-mulit-user-select v-model="users.record" :disabled="disableEditSubmit"></tl-ref-mulit-user-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-form-item label-width="0">
            <tl-help>
              默认所有会议参与人可查看会议纪要，如需给参与人之外人员纪要查看权限，请在此处添加。
            </tl-help>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="23">
          <el-form-item label="录音授权">
            <tl-ref-mulit-user-select v-model="users.audio" :disabled="disableEditSubmit"></tl-ref-mulit-user-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-form-item label-width="0">
            <tl-help>
              默认所有会议参与人可查看会议录音，如需给参与人之外人员录音查看权限，请在此处添加。
            </tl-help>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-meet-room-item-ref ref="meetRoomRef" @confirm="doSubmitMeetRoom" :isSingleSelect="true"></tl-meet-room-item-ref>
  </div>
</template>
<script>
/** mixins */
import { mixin_edit } from '@tapui/mixins/mixin_edit'
import { formatDate } from '@tapui/utils/date'
import { queryDataCode } from '@tapui/api/dataCode'
/** 子组件 */
import tlTaskManage from '../taskManage/index'
import tlFileManage from '../fileManage/index'
import tlTaskMaster from '../taskMaster/index'
import tlTaskDetail from '../taskDetail/index'
import tlMeetAgenda from '../meetAgenda/index'
import tlMeetRecordEdit from '../meetRecord/edit'
import tlMeetRoomItemRef from '../meetRoomManage/refList'
import tlRefMeetType from '../meetTypeManage/refMeetType'
import tlRefMulitUserSelect from '@/components/common/refMulitUserSelect'
import uploadComp from "./uploadComp"
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { tlTaskManage, tlFileManage, tlTaskMaster, tlTaskDetail, tlMeetAgenda, tlRefMeetType, tlMeetRecordEdit, tlRefMulitUserSelect, tlMeetRoomItemRef, uploadComp },
  data() {
    return {
      moduleTitle: '会议资料',
      urlPrefix: '/meet/record/',
      activeTab: 'basic',
      url: {
        add: '/meet/record/save',
        edit: '/meet/record/save',
        queryTeamList: 'base/teamInfo/list', // 查询团队
        queryVisibleTeamList: 'base/teamInfo/list?qry_visible=1', // 查询可见团队
        publish: 'meet/record/publish', // 发布
        cancel: 'meet/record/cancel', // 取消
        queryUser: '/base/permissionManage/queryList', // 查询人员
        queryMeetTypeList: '/meet/typeManage/queryTreeList',
        collect: 'base/operateRecord/operateState' // 收藏
      },
      queryBoardItemModel: {
        begintime: '',
        endtime: '',
        count: 0
      },
      teamRefTitle: '团队选择',
      isQueryInitData: true,
      selectedMembers: {},
      isMemberSearch: false,
      activeNames: ['baseinfo', 'place', 'launchorg', 'notice'],
      users: {},
      selectmeettypelist: [],
      meetTypeList: [],
      ehrsourceid: '', // 人力系统专用
      fromehr: '' // 人力系统专用
    }
  },
  props: {
    sourceType: {
      type: String,
      default: 'meetCreate'
    }
  },
  computed: {
    // 计算参会人员数目
    attendUserCount() {
      let count = 0
      for (let index in this.model.basesharelist) {
        let item = this.model.basesharelist[index]
        if (item.sharetype === 'attend' && item.allusernames) {
          count = item.allusernames.split(',').length
          break
        }
      }
      return count
    }
  },
  methods: {
    loaded() {
      if (this.fromehr !== '1') {
        this.activeTab = 'basic'
      }
      // 新建会议时，页面加载完毕执行
      if (this.model.state === 2) {
        this.disableEditSubmit = true
      }
      this.isMemberSearch = false
      this.remindId = -1
      if (!this.isAdd) {
        // 编辑
        this.processTime()
        this.queryUser()
      } else {
        // 新增
        this.$set(this.model, 'enabled', 1)
        this.$set(this.model, 'sortcode', 0)
        this.$set(this.model, 'launchusercode', this.user.code)
        this.$set(this.model, 'launchusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'launchorgtype', 'dept')
        this.$set(this.model, 'launchorgindex', this.dept.code)
        this.$set(this.model, 'launchorgname', this.dept.fullname)
        this.$set(this.model, 'begintimeDate', formatDate(new Date(), 'yyyy-MM-dd'))
        this.$set(this.model, 'endtimeDate', formatDate(new Date(), 'yyyy-MM-dd'))
        this.$set(this.model, 'begintimeTime', '09:00')
        this.$set(this.model, 'endtimeTime', '11:00')
        // 纪要查阅
        this.initUsers('record')
        // 录音
        this.initUsers('audio')
      }
    },
    processTime() {
       // 时间拆分
      if (this.model.begintime) {
        let beginArr = this.model.begintime.split(' ')
        this.$set(this.model, 'begintimeDate', beginArr[0])
        this.$set(this.model, 'begintimeTime', beginArr[1].substring(0, 5))
      } else {
        this.$set(this.model, 'begintimeDate', '')
        this.$set(this.model, 'begintimeTime', '')
      }
      if (this.model.endtime) {
        let endArr = this.model.endtime.split(' ')
        this.$set(this.model, 'endtimeDate', endArr[0])
        this.$set(this.model, 'endtimeTime', endArr[1].substring(0, 5))
      } else {
        this.$set(this.model, 'endtimeDate', '')
        this.$set(this.model, 'endtimeTime', '')
      }
    },
    // tab切换
    tabClick(tab) {
      let tabName = tab.name
      if (tabName === 'taskManage') {
        this.$nextTick(_ => {
          this.$refs.taskManage.loadData({})
        })
      } else if (tabName === 'taskMaster') {
        this.$nextTick(_ => {
          this.$refs.taskMaster.loadData({})
          this.$refs.taskMaster.queryDataCodeList()
        })
      } else if (tabName === 'taskDetail') {
        this.$nextTick(_ => {
          this.$refs.taskDetail.loadData({})
        })
      } else if (tabName === 'file') {
        this.$nextTick(_ => {
          this.$refs.fileManage.loadData({})
        })
      } else if (tabName === 'meetAgenda') {
        this.$nextTick(_ => {
          this.$refs.meetAgenda.loadData({})
        })
      } else if (tabName === 'minutes') {
        this.$nextTick(_ => {
          this.$refs.attachment.initData()
        })
      }
    },
    /** 重写编辑，发请求获得数据 */
    queryData(id) {
      if (!this.url.load) {
        this.$tap.alert('请设置load地址!', 'warning')
        return
      }
      return getAction(this.url.load, { id: id, operatetype: this.sourceType }).then(res => {
        if (res.success) {
          this.model = res.result
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 当切换组织类型时，清空组织信息
    clearOrgInfo() {
      this.$set(this.model, 'launchorgindex', '')
      this.$set(this.model, 'launchorgname', '')
    },
    /** 提交前检查 */
    beforeSubmit() {
      this.model.begintime = `${this.model.begintimeDate} ${this.model.begintimeTime}`
      this.model.endtime = `${this.model.endtimeDate} ${this.model.endtimeTime}`
      let beginTime = new Date(this.model.begintime)
      let endTime = new Date(this.model.endtime)
      if (endTime <= beginTime) {
        this.$tap.alert('会议结束时间不能早于会议开始时间！')
        return false
      }
      this.model.selectUsers = this.users
      return true
    },
    /** 重写新增提交，不关闭对话框 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      postAction(this.url.add + '?billuid=' + this.uid, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            let meetType = this.model.selectmeettypelist
            this.model = res.result
            this.model.selectmeettypelist = meetType
            // 处理时间
            this.processTime()
            this.isAdd = false
            this.$emit('refresh')
            this.postEHRMessage()
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    /** 重写编辑提交，不关闭对话框 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message(res.message, 'success')
            this.$emit('refresh')
            this.postEHRMessage()
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    // 执行发布会议
    doSubmitIssue() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$tap
            .confirm('是否发布会议资料？')
            .then(_ => {
              if (!this.beforeSubmit() || !this.checkRecordFile()) {
                return
              }
              // 若是人力系统调用则传fromehr参数
              if (this.fromehr === '1') {
                this.$set(this.model, 'fromehr', this.fromehr)
              }
              postAction(this.url.publish, this.model).then(res => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  this.$emit('refresh')
                  this.postEHRMessage()
                  this.visible = false
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
              })
            })
            .catch(_ => {})
        } else {
          return false
        }
      })
    },
    /** 收藏 */
    doCollect() {
      this.saveLoading = true
      postAction(this.url.collect, { sourcetype: 'MeetRecord', sourceid: this.model.id, operatetype: 'collect' })
        .then(res => {
          if (res.success) {
            this.$tap.message('收藏成功', 'success')
            this.model.iscollect = 1
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    /** 取消收藏 */
    doCancelCollect() {
      this.saveLoading = true
      postAction(this.url.collect, { sourcetype: 'MeetRecord', sourceid: this.model.id, operatetype: 'collect' })
        .then(res => {
          if (res.success) {
            this.$tap.message('取消收藏成功', 'success')
            this.model.iscollect = 0
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    // 检查有没有上传纪要文件
    checkRecordFile() {
      let fileCount = 0
      if (this.$refs.attachment.fileList.length > 0) {
        fileCount = this.$refs.attachment.fileList.length
      } else {
        fileCount = this.$refs.attachment.fileCount
      }
      if (fileCount === 0 && this.fromehr !== '1') {
        this.$tap.alert('没有上传会议纪要文件，不能发布！')
        return false
      }
      return true
    },
    // 取消会议室审批，将会议状态置为作废
    doCancelMeet() {
      this.$tap
        .confirm('是否将纪要作废？作废后不可恢复！')
        .then(_ => {
          postAction(this.url.cancel, this.model).then(res => {
            if (res.success) {
              this.disableEditSubmit = true
              this.$tap.message(res.message, 'success')
              this.$emit('refresh')
            } else {
              this.$tap.alert('作废失败', 'warning')
            }
          })
        })
        .catch(_ => {})
    },
    // 查询人员
    queryUser() {
      getAction(this.url.queryUser, { qry_sourcetype: 'MeetRecord', qry_sourceid: this.model.id }).then(res => {
        if (res.success) {
          this.users = {}
          // 纪要查阅
          this.initUsers('record')
          // 录音
          this.initUsers('audio')
          res.result.forEach(m => {
            if (m.sharetype === '5') {
              this.users[m.sourceflag].usernames = m.shareobjectsdesc
              this.users[m.sourceflag].usercodes = m.shareobjects
            } else if (m.sharetype === '1') {
              this.users[m.sourceflag].deptnames = m.shareobjectsdesc
              this.users[m.sourceflag].deptcodes = m.shareobjects
            } else if (m.sharetype === '3') {
              this.users[m.sourceflag].rolenames = m.shareobjectsdesc
              this.users[m.sourceflag].roleids = m.shareobjects
            } else if (m.sharetype === '2') {
              this.users[m.sourceflag].teamnames = m.shareobjectsdesc
              this.users[m.sourceflag].teamids = m.shareobjects
            }
          })
        }
      })
    },
    /** 初识用户数据 */
    initUsers(sourceflag) {
      let user = {
        usernames: '',
        usercodes: '',
        deptnames: '',
        deptcodes: '',
        teamids: '',
        teamnames: '',
        roleids: '',
        rolenames: ''
      }
      // 注意一定不要使用,this.users[sourceflag]=user赋值，这种情况无法渲染界面，不能实现双向绑定。
      this.$set(this.users, sourceflag, user)
    },
    /** 打开会议室参照 */
    openMeetRoomRefDialog() {
      this.$refs.meetRoomRef.visible = true
    },
    /** 选择会议室 */
    doSubmitMeetRoom(selectData) {
      if (selectData.length === 0) {
        this.$set(this.model, 'meetroomid', '')
        this.$set(this.model, 'airlinecompany', '')
        this.$set(this.model, 'place', '')
      } else {
        this.$set(this.model, 'meetroomid', selectData.id)
        this.$set(this.model, 'airlinecompany', selectData.name + '(' + selectData.locationdesc + ')')
        this.$set(this.model, 'place', selectData.name + '(' + selectData.locationdesc + ')')
      }
    },
    handleMeetTypeChange(value) {
      if (typeof value !== 'undefined') {
        this.model.meettypeid = value[value.length - 1]
      }
    },
    /** 发送事件 */
    postEHRMessage() {
       window.parent.postMessage('submitAfter:' + this.model.id + ';' + this.ehrsourceid, '*')
    },
    /** 切换tab页到录音文件页 */
    changeTabToAudio() {
      this.activeTab = 'file'
    },
    /** 提醒上传录音文件成功 */
    remindSuccess(num) {
      window.parent.postMessage('audio:' + num + ';' + this.ehrsourceid, '*')
    }
  },
  created() {
    /** 查询会议类型树 */
    getAction(this.url.queryMeetTypeList, { isAddRoot: false }).then(res => {
      if (res.success) {
        let reg = new RegExp('id', 'g') // g代表全部
        this.meetTypeList = JSON.parse(JSON.stringify(res.result.dataList).replace(reg, 'value'))
      }
    })
  }
}
</script>
<style scoped lang="scss">
.tag-container {
  .el-tag {
    margin-right: 5px;
  }
}
.color-block {
  display: inline-block;
  height: 15px;
  width: 15px;
}
.input-with-select {
  .el-select {
    width: 80px;
  }
}
</style>
<style lang="scss">
.page .share-content {
  margin-left: 15px;
  margin-bottom: 5px;
}
.page .label-content {
  color: #409eff;
}
.page .el-collapse-item__header {
  color: blue;
}

.page .el-divider__text {
  color: blue;
}
.page .el-row {
  margin-right: 40px;
}
.page .el-divider--horizontal {
  margin: 14px 0;
}
.page .meetTitle {
  padding-top: 5px;
  padding-bottom: 10px;
  padding-left: 30px;
}
.page .meetInfo {
  color: black;
  font-size: 14px;
  font-weight: bold !important;
  vertical-align: middle;
}
</style>
